package com.pansoft.xmlparse;

import android.text.TextUtils;

import com.core.xml.StubObject;
import com.efounder.service.Registry;
import com.pansoft.resmanager.ResFileManager;
import com.pansoft.resmanager.ResLoadManager;

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;
import org.xml.sax.InputSource;

import java.io.File;
import java.io.StringReader;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;

/**
 * Option配置文件解析，以前是重新解析了一遍文件，现在改成读取 registery中的
 *
 * @author yqs 20191113
 */
public class OptionParser {
    private static String TAG_SERVICE = "node";
    private static OptionParser optionParser;
//    private NodeList nodeList;

    private OptionParser() {
        super();
//        String resPath = ResLoadManager.getTabMenuPath() + File.separator + "Option.xml";
//        nodeList = parseXML(resPath);
    }

    public static synchronized OptionParser getInstance() {
        if (optionParser == null) {
            optionParser = new OptionParser();
        }
        return optionParser;
    }

    private NodeList parseXML(String path) {
        NodeList nodeList = null;
        File file = new File(path);
        String xmlString = ResFileManager.decryptFile(file);
        try {
            Element rootElement = stringToElement(xmlString);
            String id = rootElement.getAttribute("id");
            if ("option".equals(id)) {
                nodeList = rootElement.getElementsByTagName(TAG_SERVICE);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return nodeList;
    }

    public Map<String, String> getElementById(String id) {


        StubObject stubObject = Registry.getRegEntry(id);
        if (stubObject == null) {
            return null;
        }

        Map<String, String> map = new HashMap<>();
        for (Object key : stubObject.getStubTable().keySet()) {
            map.put(key.toString(), stubObject.getStubTable().get(key).toString());
        }
        return map;
//        if (nodeList == null) {
//            return null;
//        }
//        for (int i = 0; i < nodeList.getLength(); i++) {
//            Element element = (Element) nodeList.item(i);
//            String tempId = element.getAttribute("id");
//            if (tempId != null && tempId.equals(id)) {
//                NamedNodeMap namedNodeMap = element.getAttributes();
//                Map<String, String> map = new HashMap<String, String>();
//                for (int j = 0; j < namedNodeMap.getLength(); j++) {
//                    Attr attr = (Attr) namedNodeMap.item(j);
//                    map.put(attr.getName(), attr.getValue());
//                }
//                try {
//                    //添加多语言支持
//                    if(map.get(ResStringUtil.MULTI_LANGUAGE_KEY)!=null&&!map.get(ResStringUtil.MULTI_LANGUAGE_KEY).equals("")){
////                        if (ResLoadManager.getrFile()!=null){
////                            map.put(ResStringUtil.CAPTION,ResStringUtil.getString(ResStringUtil.getResIdByString(
////                                    (Class)ResLoadManager.getrFile(),map.get(ResStringUtil.MULTI_LANGUAGE_KEY))));
////                        }else{
//                            map.put(ResStringUtil.CAPTION,ResStringUtil.getString(ResStringUtil.getResIdByString(
//                                    R.string.class,map.get(ResStringUtil.MULTI_LANGUAGE_KEY))));
//                       // }
//
//                    }
//                }catch (Exception e){
//                    e.printStackTrace();
//                }
//                return map;
//            }
//        }
//        return null;
    }

    /**
     * 通过属性名查找节点
     * <p>
     * 这个方法只给旧项目使用，严禁新的代码中使用！！！！！！！！！！！！
     *
     * @param attrName
     * @return
     */
    @Deprecated
    public List<Element> getElementsByAttr(String attrName) {
        String resPath = ResLoadManager.getTabMenuPath() + File.separator + "Option.xml";
        NodeList nodeList = parseXML(resPath);
        ArrayList<Element> elements = new ArrayList<>();
        if (TextUtils.isEmpty(attrName)) {
            throw new IllegalArgumentException("attr can not  null");
        }
        for (int i = 0; i < nodeList.getLength(); i++) {
            Element element = (Element) nodeList.item(i);
            if (element.hasAttribute(attrName)) {
                elements.add(element);

            }
        }
        return elements;
    }

    /**
     * 灏�瀛�绗�涓茶浆���涓�element
     *
     * @param xml
     * @return
     * @throws Exception
     */
    public static Element stringToElement(String xml) throws Exception {
        StringReader sr = new StringReader(xml);
        InputSource is = new InputSource(sr);
        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
        DocumentBuilder builder = factory.newDocumentBuilder();
        Document doc = builder.parse(is);
        Element rootElement = doc.getDocumentElement();
        return rootElement;

    }

    public void release() {
        optionParser = null;
    }

}
